<template>
  <div class="home-page">
    <!-- 上半部分背景图 -->
    <div class="hero">
      <div class="hero-title">
        电商数据中的用户特征分析
      </div>
      <div class="hero-text">
        已收录562859条数据
      </div>
    </div>

    <!-- 下半部分导航 + 卡片 -->
    <div class="content">
      <div class="nav-bar-wrapper">
        <!-- 左箭头 -->
        <span 
          class="arrow left" 
          @click="prev"
        >⬅</span>

        <!-- 导航项（使用 displayNavItems 来保证循环显示） -->
        <div class="nav-bar">
          <span
            v-for="(item, idx) in displayNavItems"
            :key="item.originalIndex"
            :style="itemStyle(item.originalIndex)"
            :class="{ active: activeIndex === item.originalIndex }"
            @click="switchNav(item.originalIndex)"
          >
            {{ item.label }}
          </span>
        </div>

        <!-- 右箭头 -->
        <span 
          class="arrow right" 
          @click="next"
        >➡</span>
      </div>

      <!--  卡片展示（支持任意数量卡片） -->
      <div v-if="activeCards && activeCards.length" class="card-wrapper cards-row">
        <div
          v-for="(card, pos) in arrangedCards"
          :key="card.key"
          class="card card-three"
          :class="{
            'center': card.originalIndex === selectedCardIndex,
            'left': card.arrangedPos < Math.floor(arrangedCards.length / 2),
            'right': card.arrangedPos > Math.floor(arrangedCards.length / 2),
            'armed': centerClickArmed && card.originalIndex === selectedCardIndex,
            'swapping': card.swapping
          }"
          @click.stop="onCardClick($event, card.originalIndex, card)"
          :style="{ 
            backgroundImage: `url(${card.bg})`, 
            zIndex: (card.originalIndex === selectedCardIndex ? 30 : 10 - Math.abs(card.arrangedPos - Math.floor(arrangedCards.length / 2))),
            transform: getCardTransform(card.arrangedPos),
            left: getCardPosition(card.arrangedPos),
            transition: getCardTransition(card)
          }"
          @transitionend="onTransitionEnd(card)"
        >
          <div class="card-inner">
            <div class="card-title">{{ card.title || activeItem.label }}</div>
          </div>
          <!-- 点击涟漪效果 -->
          <div v-if="card.ripple" class="ripple" :style="card.rippleStyle"></div>
        </div>
      </div>
    </div>

    <FeaturesSection />
    <FooterInfo />
  </div>
</template>

<script>
import FeaturesSection from '../components/FeaturesSection.vue'
import FooterInfo from '../components/FooterInfo.vue'
import axios from 'axios';

export default {
  name: "HomePage",
  components: { FeaturesSection, FooterInfo },
  data() {
    return {
      total: 0,
      activeIndex: 2,
      selectedCardIndex: 1,
      centerClickArmed: false, 
      swappingCards: false,
      navItems: [
        { label: "性别", cards: 
        [// { title: "按地区和性别查看品牌销售数量和金额", path: "/page5", bg: "/public/999.jpg" }, 
          { title: "性别对产品的购买倾向分析", path: "/page1", bg: "/public/141.jpg" }, 
         //{ title: "性别", path: "/page1", bg: "/public/banner2.jpg" }
        ] },
        { label: "年龄", cards:
        [ { title: "不同年龄段品牌销售分析", path: "/page7", bg: "/public/747.jpg" }, 
          { title: "不同年龄段购买情况分析", path: "/page2", bg: "666.jpg" }, 
          { title: "不同年龄段的平均消费能力", path: "/page6", bg: "/public/000.jpg" } 
        ] },
        { label: "地区", cards:
        [ //{ title: "按地区与年龄统计品牌销售情况", path: "/page4", bg: "/public/777.jpg" }, 
          { title: "各地区平均消费能力分析", path: "/page3", bg: "/public/343.jpg" }, 
          //{ title: "按地区和性别查看品牌销售数量和金额", path: "/page5", bg: "/public/369.png" }
        ] },
        { label: "品牌", cards: 
        [ { title: "主要电子产品销售情况分析", path: "/page9", bg: "/public/lll.jpg" }, 
          { title: "各品牌销量与总销售额分析", path: "/page8", bg: "/public/ppp.jpg" }, 
          { title: "用户购买次数分布分析", path: "/page11", bg: "/public/rrr.jpg" } 
        ] },
        { label: "时间", cards: 
        [// { title: "时间", path: "/page5", bg: "/public/banner2.jpg" }, 
          { title: "2020年每月销售情况分析", path: "/page10", bg: "/public/ddd.jpg" }, 
          //{ title: "时间", path: "/page5", bg: "/public/banner2.jpg" } 
        ] },
      ],
      itemWidth: 80,
    };
  },
  computed: {
    activeItem() {
      return this.navItems[this.activeIndex] || null;
    },

    activeCards() {
      const base = this.navItems[this.activeIndex] || {};
      const cards = Array.isArray(base.cards) && base.cards.length ? base.cards.slice() : null;
      if (cards && cards.length) return cards;
      const fallback = [
        { title: `${base.label || '项'} - A`, path: base.path, bg: base.bg || '/banner2.jpg' }
      ];
      return fallback;
    },

    arrangedCards() {
      const cards = this.activeCards || [];
      const centerIndex = this.selectedCardIndex;
      const total = cards.length;
      
      if (total === 0) return [];
      
      const arranged = [];
      const centerPos = Math.floor(total / 2);
      
      arranged[centerPos] = { 
        ...cards[centerIndex], 
        originalIndex: centerIndex,
        arrangedPos: centerPos,
        key: `${this.activeIndex}-${centerIndex}-center`,
        swapping: this.swappingCards,
        ripple: false
      };
      
      let leftPos = centerPos - 1;
      let rightPos = centerPos + 1;
      
      for (let distance = 1; distance <= total; distance++) {
        const rightIndex = (centerIndex + distance) % total;
        if (rightIndex !== centerIndex && rightPos < total) {
          arranged[rightPos] = { 
            ...cards[rightIndex], 
            originalIndex: rightIndex,
            arrangedPos: rightPos,
            key: `${this.activeIndex}-${rightIndex}-right`,
            swapping: this.swappingCards,
            ripple: false
          };
          rightPos++;
        }
        
        const leftIndex = (centerIndex - distance + total) % total;
        if (leftIndex !== centerIndex && leftPos >= 0) {
          arranged[leftPos] = { 
            ...cards[leftIndex], 
            originalIndex: leftIndex,
            arrangedPos: leftPos,
            key: `${this.activeIndex}-${leftIndex}-left`,
            swapping: this.swappingCards,
            ripple: false
          };
          leftPos--;
        }
      }
      
      return arranged.filter(card => card !== undefined);
    },

    displayNavItems() {
      const len = this.navItems.length;
      if (len === 0) return [];
      const centerPos = Math.floor(len / 2);
      const arr = [];
      for (let i = 0; i < len; i++) {
        const originalIndex = (this.activeIndex - centerPos + i + len) % len;
        arr.push({
          ...this.navItems[originalIndex],
          originalIndex
        });
      }
      return arr;
    }
  },
  methods: {
    getCardPosition(arrangedPos) {
      const totalCards = this.arrangedCards.length;
      const centerIndex = Math.floor(totalCards / 2);
      
      const cardWidth = 220;
      const gap = 40;
      
      const offset = (arrangedPos - centerIndex) * (cardWidth + gap);
      return `calc(50% + ${offset}px)`;
    },

    getCardTransform(arrangedPos) {
      const totalCards = this.arrangedCards.length;
      const centerIndex = Math.floor(totalCards / 2);
      
      if (arrangedPos === centerIndex) {
        return 'translate(-50%, -50%) scale(1.25) rotateY(0deg)';
      } else {
        const rotation = arrangedPos < centerIndex ? '5deg' : '-5deg';
        return `translate(-50%, -50%) scale(0.9) rotateY(${rotation})`;
      }
    },

    getCardTransition(card) {
      if (card.swapping) {
        return 'all 0.6s cubic-bezier(0.34, 1.56, 0.64, 1)';
      } else if (card.originalIndex === this.selectedCardIndex) {
        return 'all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
      } else {
        return 'all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
      }
    },

    onTransitionEnd(card) {
      if (card.swapping) {
        card.swapping = false;
      }
    },

    // 修复：添加事件参数
    createRippleEffect(event, card) {
      if (!event || !event.currentTarget) {
        console.warn('Event or currentTarget is undefined');
        return;
      }
      
      const rect = event.currentTarget.getBoundingClientRect();
      const size = Math.max(rect.width, rect.height);
      const x = event.clientX - rect.left - size / 2;
      const y = event.clientY - rect.top - size / 2;
      
      card.ripple = true;
      card.rippleStyle = {
        width: `${size}px`,
        height: `${size}px`,
        left: `${x}px`,
        top: `${y}px`
      };
      
      setTimeout(() => {
        card.ripple = false;
      }, 2000);
    },

    goTo(path) {
      if (!path || path === '#') return;
      if (this.$route && this.$route.path === path) return;
      this.$router.push(path);
    },

    switchNav(index) {
      this.activeIndex = index;
      const count = (this.navItems[index] && Array.isArray(this.navItems[index].cards)) ? this.navItems[index].cards.length : 1;
      this.selectedCardIndex = Math.floor(count / 2);
      this.centerClickArmed = true;
      this.$router.replace({
        query: { ...this.$route.query, activeIndex: index }
      });
    },

    // 修复：调整参数顺序，事件对象放在第一位
    onCardClick(event, originalIndex, card) {
      // 添加涟漪效果
      this.createRippleEffect(event, card);
      
      if (originalIndex !== this.selectedCardIndex) {
        this.swappingCards = true;
        
        setTimeout(() => {
          this.selectedCardIndex = originalIndex;
          this.centerClickArmed = true;
          
          setTimeout(() => {
            this.swappingCards = false;
          }, 600);
        }, 150);
      } else {
        if (this.centerClickArmed) {
          card.swapping = true;
          setTimeout(() => {
            this.goTo(card.path);
            this.centerClickArmed = false;
          }, 300);
        } else {
          this.centerClickArmed = true;
        }
      }
    },

    async getCleanedData(hdfspath, limit) {
      try {
        const response = await axios.get('https://api.example.com/hdfspath', {
          params: { hdfspath, limit }
        });
        if (response.data.code === 200) {
          const data = response.data.data;
          console.log('清洗后的数据:', data);
          return data;
        } else {
          console.error('接口返回异常:', response.data);
          return [];
        }
      } catch (error) {
        console.error('请求失败:', error);
        return [];
      }
    },

    prev() {
      this.swappingCards = true;
      const len = this.navItems.length;
      if (len === 0) return;
      this.switchNav((this.activeIndex - 1 + len) % len);
      setTimeout(() => {
        this.swappingCards = false;
      }, 600);
    },

    next() {
      this.swappingCards = true;
      const len = this.navItems.length;
      if (len === 0) return;
      this.switchNav((this.activeIndex + 1) % len);
      setTimeout(() => {
        this.swappingCards = false;
      }, 600);
    },

    itemStyle(originalIndex) {
      const len = this.navItems.length;
      if (len === 0) return {};
      let diff = Math.abs((originalIndex - this.activeIndex + len) % len);
      const distance = Math.min(diff, len - diff);

      const opacity = 1 - Math.min(distance * 0.15, 0.5);
      const blur = Math.min(distance * 1.2, 3);
      return {
        opacity,
        filter: `blur(${blur}px)`,
        pointerEvents: distance <= 1 ? "auto" : "none"
      };
    }
  },
  mounted() {
    const qIndex = parseInt(this.$route.query.activeIndex, 10);
     if (!isNaN(qIndex)) {
       this.activeIndex = qIndex;
     }
    const initialCount = (this.navItems[this.activeIndex] && Array.isArray(this.navItems[this.activeIndex].cards)) ? this.navItems[this.activeIndex].cards.length : 1;
    this.selectedCardIndex = Math.floor(initialCount / 2);
    this.centerClickArmed = true;
    this.getCleanedData("somePath", 500)
  }
};
</script>

<style scoped>
.home-page { 
  display: flex; 
  flex-direction: column; 
  min-height: 100vh; 
}

.hero { 
  height: 400px; 
  background-image: url('/banner3.jpg'); 
  background-size: cover; 
  background-position: center; 
  display: flex; 
  flex-direction: column; 
  justify-content: center; 
  align-items: center; 
  text-align: center; 
  position: relative; 
  color: white; 
}

.hero-title { 
  font-size: 48px; 
  font-weight: 1000; 
  color: #6f6969; 
  margin-bottom: 20px; 
  text-shadow: 0 4px 12px rgba(0, 0, 0, 0.4); 
}

.hero-text { 
  font-size: 20px; 
  font-weight: bold; 
  text-shadow: 0 2px 6px rgba(0,0,0,0.5); 
}

.content { 
  flex: 0 0 auto; 
  display: flex; 
  flex-direction: column; 
  align-items: center; 
  padding: 40px 20px; 
}

.nav-bar-wrapper { 
  width: 600px; 
  max-width: 90%; 
  margin: 0 auto 20px; 
  position: relative; 
  overflow: hidden; 
}

.nav-bar { 
  display: flex; 
  gap: 20px; 
  transition: transform 0.5s ease; 
  justify-content: center; 
  align-items: center; 
}

.nav-bar span { 
  cursor: pointer; 
  font-size: 12px; 
  padding: 5px 12px; 
  transition: color 0.3s, border-bottom 0.3s, opacity 0.3s, filter 0.3s; 
}

.nav-bar span.active { 
  color: #da8cd6; 
  border-bottom: 2px solid #ca89d5; 
  font-weight: bold; 
}

.arrow { 
  position: absolute; 
  top: 50%; transform: translateY(-50%); 
  font-size: 24px; 
  font-weight: bold; 
  cursor: pointer; 
  user-select: none; 
  color: #db8abd; 
  background: none; 
  padding: 0; 
  box-shadow: none; 
  z-index: 2; 
  transition: transform 0.3s ease, color 0.3s ease;
}

.arrow:hover {
  transform: translateY(-50%) scale(1.2);
  color: #ff6b9d;
}

.arrow.left { left: 10px; }

.arrow.right { right: 10px; }

.card-wrapper { 
  position: relative;
  width: 100%;
  height: 220px;
  margin: 40px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  perspective: 1000px;
}

.card-three { 
  width: 220px;
  height: 140px;
  border-radius: 12px; 
  overflow: hidden; 
  position: absolute; 
  top: 50%;
  display: flex; 
  justify-content: center; 
  align-items: flex-end; 
  box-shadow: 0 10px 25px rgba(0,0,0,0.15); 
  background: #fff; 
  background-size: cover; 
  background-position: center; 
  transform-style: preserve-3d;
}

.card-three:hover {
  transform: translate(-50%, -50%) scale(1.05) rotateY(5deg);
  box-shadow: 0 15px 35px rgba(0,0,0,0.2);
}

.card-three::before {
  content: "";
  position: absolute;
  inset: 0;
  background: linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0));
  z-index: 1;
  transition: opacity 0.3s ease;
}

.card-three:hover::before {
  opacity: 0.8;
}

.card-three .card-inner {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 12px;
  text-align: center;
  z-index: 2;
  transition: transform 0.3s ease;
}

.card-three:hover .card-inner {
  transform: translateY(-5px);
}

.card-three .card-title {
  color: #fff;
  font-weight: 700;
  font-size: 16px;
  text-shadow: 0 2px 6px rgba(0,0,0,0.6);
  line-height: 1.4;
  transition: all 0.3s ease;
}

.card-three:hover .card-title {
  font-size: 17px;
}

.card-three.center { 
  z-index: 30; 
  box-shadow: 0 20px 40px rgba(0,0,0,0.25); 
  opacity: 1; 
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translate(-50%, -50%) scale(1.25) translateY(0px); }
  50% { transform: translate(-50%, -50%) scale(1.25) translateY(-10px); }
}

.card-three.left, .card-three.right { 
  opacity: 0.9; 
  box-shadow: 0 6px 15px rgba(0,0,0,0.12); 
}

.card-three.swapping {
  animation: swapPulse 0.6s ease-in-out;
}

@keyframes swapPulse {
  0% { transform: translate(-50%, -50%) scale(1); }
  50% { transform: translate(-50%, -50%) scale(1.1); }
  100% { transform: translate(-50%, -50%) scale(1); }
}

.card-three.center.armed { 
  outline: 3px solid rgba(66,184,131,0.3); 
  box-shadow: 0 25px 50px rgba(66,184,131,0.3); 
  animation: armedPulse 1s infinite;
}

@keyframes armedPulse {
  0%, 100% { outline-color: rgba(66,184,131,0.3); }
  50% { outline-color: rgba(66,184,131,0.6); }
}

.ripple {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.6);
  transform: scale(0);
  animation: ripple 0.6s linear;
  pointer-events: none;
}

@keyframes ripple {
  to {
    transform: scale(4);
    opacity: 0;
  }
}

.card-three {
  /*animation: fadeInUp 0.5s ease-out;*/
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translate(-50%, -30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

@media (max-width: 720px) {
  .card-wrapper { 
    height: 180px; 
    margin: 30px 0; 
  }
  
  .card-three { 
    width: 180px; 
    height: 120px; 
  }
  
  .card-three .card-title {
    font-size: 14px;
    padding: 8px;
  }
  
  .card-three:hover .card-title {
    font-size: 15px;
  }
}

footer { margin-top: auto; }
</style>